package com.lh.web.ctrl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lh.annotation.UserType;
import com.lh.biz.IUserBiz;
import com.lh.biz.dto.in.user.ForgetPasswordInDto;
import com.lh.biz.dto.in.user.LoginInDto;
import com.lh.biz.dto.in.user.RegisteInDto;
import com.lh.biz.dto.in.user.ResetPasswordInDto;
import com.lh.biz.dto.out.user.ForgetPasswordOutDto;
import com.lh.biz.dto.out.user.LoginOutDto;
import com.lh.biz.dto.out.user.RegisteOutDto;
import com.lh.cache.CacheManager;
import com.lh.ctrl.BaseCtrl;
import com.lh.entity.Cart;
import com.lh.entity.User.ForgetPasswordToken;
import com.lh.exception.BizException;
import com.lh.util.SessionUtil;

/**
 * @author liuhui
 * @version 1.0
 * @date 2013-4-5 下午12:43:53
 */
@Controller
@RequestMapping("user")
public  class UserCtrl extends BaseCtrl {
	
	@Resource
	private IUserBiz userBiz;
	@Resource
	private CacheManager cacheManager;
	
	
	@ResponseBody
	@RequestMapping(value="login" , method=RequestMethod.POST)
	public LoginOutDto login(@Valid LoginInDto inDto, HttpServletRequest request ,HttpServletResponse response) throws BizException{
		
		inDto.setRemoteAddress(request.getRemoteAddr());
		String cartId = getCookieValue(request.getCookies(), Cart.CART_COOKIE_NAME);
		if(StringUtils.isNotBlank(cartId)){
			inDto.setCartId(Long.parseLong(cartId));
		}
		LoginOutDto out =  userBiz.login(inDto);
		
		addCookie(response, IUserBiz.SESSION_TOKEN_NAME, out.getSessionToken(), -1 );
		
		return out;
	}
	
	@RequestMapping(value="logout")
	@ResponseBody
	public JSONObject logout(HttpServletResponse response){
		addCookie(response, IUserBiz.SESSION_TOKEN_NAME, null , 0 );
		SessionUtil.setUser(null);
		return getSuccessJsonResult();
	}
	
	@RequestMapping(value="login" , method=RequestMethod.GET)
	public void toLogin(Model model){
		model.addAttribute("user", SessionUtil.getUser());
	}
	
	
	@RequestMapping(value="registe" , method=RequestMethod.GET)
	public void toRegiste( ){
		
	}
	@ResponseBody
	@RequestMapping(value="registe" , method=RequestMethod.POST)
	public RegisteOutDto registe(@Valid RegisteInDto inDto  , HttpServletRequest request , HttpServletResponse response) throws BizException{
		RegisteOutDto out = null;
		String validCode = (String) request.getSession(true).getAttribute(CommonCtrl.VALID_CODE_NAME);
		if(validCode == null || !validCode.equalsIgnoreCase(inDto.getValidCode())){
			out = new RegisteOutDto();
			out.setSuccess(false);
			out.setMessage(getMessage("common.validCodeError"));
			return out;
		}
		inDto.setRemoteAddress(request.getRemoteAddr());
		String cartId = getCookieValue(request.getCookies(), Cart.CART_COOKIE_NAME);
		if(StringUtils.isNotBlank(cartId)){
			inDto.setCartId(Long.parseLong(cartId));
		}
		out = userBiz.registe(inDto);
		addCookie(response, IUserBiz.SESSION_TOKEN_NAME, out.getSessionToken(), -1 );
		return out;
	}
	
	@RequestMapping(value="forget-password" , method=RequestMethod.GET)
	public void toForgetPassword(){
		
	}
	@RequestMapping(value="reset-password" , method=RequestMethod.GET)
	public void toRestPassword(Long id , String token , Model model){
		if(!cacheManager.hasKey(IUserBiz.FIND_PASSWORD_CACHE_KEY_PREFIX + id)){
			model.addAttribute("invalid", true);
			return ;
		}
		ForgetPasswordToken tokenObject = (ForgetPasswordToken) cacheManager.getValue(IUserBiz.FIND_PASSWORD_CACHE_KEY_PREFIX + id);
		if(tokenObject.isUsed() || !tokenObject.getToken().equals(token) || !tokenObject.getUserId().equals(id)){
			model.addAttribute("invalid", true);
			return ;
		}
		model.addAttribute("invalid", false);
		tokenObject.setUsed(true);
		
	}
	
	@ResponseBody
	@RequestMapping(value="reset-password" , method=RequestMethod.POST)
	public JSONObject restPassword(@Valid ResetPasswordInDto inDto  ) throws BizException{
		if(!cacheManager.hasKey(IUserBiz.FIND_PASSWORD_CACHE_KEY_PREFIX + inDto.getId())){
			throw new BizException(getMessage("user.resetPasswordError"));
		}
		ForgetPasswordToken tokenObject = (ForgetPasswordToken) cacheManager.getValue(IUserBiz.FIND_PASSWORD_CACHE_KEY_PREFIX + inDto.getId());
		if( !tokenObject.getToken().equals(inDto.getToken()) || !tokenObject.getUserId().equals(inDto.getId())){
			throw new BizException(getMessage("user.resetPasswordError"));
		}
		userBiz.resetPassword(inDto);
		cacheManager.delete(IUserBiz.FIND_PASSWORD_CACHE_KEY_PREFIX + inDto.getId());
		return getSuccessJsonResult();
	}
	
	
	
	
	@ResponseBody
	@RequestMapping(value="forget-password" , method=RequestMethod.POST)
	public ForgetPasswordOutDto forgetPassword(@Valid ForgetPasswordInDto inDto   , HttpServletRequest request) throws BizException{
		ForgetPasswordOutDto out = null;
		String validCode = (String) request.getSession(true).getAttribute(CommonCtrl.VALID_CODE_NAME);
		if(validCode == null || !validCode.equalsIgnoreCase(inDto.getValidCode())){
			out = new ForgetPasswordOutDto();
			out.setSuccess(false);
			out.setMessage(getMessage("common.validCodeError"));
			return out;
		}
		out = userBiz.forgetPassword(inDto);
		return out;
	}
	
	@RequestMapping("index")
	@UserType({UserType.Type.COMMON})
	public void index(Model model){
		model.addAttribute("user", SessionUtil.getUser());
	}
	

}
